# coding=utf-8
"""
Author: Mr.夏末
@Function: 图文验证码
"""
import os
from hashlib import md5

import requests


class Verify:
    def __init__(self, username, password, soft_id):
        """

        :param username: 用户名
        :param password: 密码
        :param soft_id: 软件ID
        """
        self.username = username
        # MD5加密
        password =  password.encode('utf8')
        self.password = md5(password).hexdigest()

        self.soft_id = soft_id
        # 初始化参数
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        # 添加头
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def get_verify(self, im, codetype='1004'):
        """
        im: 图片地址
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        # 打开图片为二进制
        im = open(im,'rb').read()
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)
        try:
            ver = r.json().get('pic_str')
        except Exception as e:
            print(e.__str__())
            ver = 'None'
        return ver

if __name__ == '__main__':
    # 创建对象
    verify = Verify('wuqingfqng','wuqing&fqng','904357')
    # verify = Verify('17863087593','hzs123456','937288')
    # 调用方法，获取验证码
    ver = verify.get_verify(os.path.join(os.path.dirname(os.path.dirname(__file__)),'lib','a.jpg'))
    print(ver)